<?php
require_once( "../Model/db_Restaurant.cls.php");
require_once( "../Model/db_CateRes.cls.php");
/*
*	Note: 
*/
class Restaurant
{
	private $clsRest; // controllers Restaurant
	private $clsCategory;
	public function __construct()
	{
		$this->clsRest = new db_restaurant();
		$this->clsCategory = new db_CateRes();
	}
	public function selectRestaurant($id)
	{
		if(empty($id))
			return;
		$result = $this->clsRest->select($id);
		return $result;
	}
	public function selectAll($id = '')
	{
		if(!empty($id))
			$this->selectRestaurant($id);
 		return $this->clsRest->selectAll();
	}
	//
	public function deleteRestaurant($id = '')
	{
		if(empty($id))
			return;
		return $this->clsRest->delete($id);
	}
	public function deleteAll()
	{
		return $this->clsRest->deleteAll();
	}
	//
	public function insertRestaurant($param = array())
	{
		if(empty($param))
			return false;
		foreach ($param as $key => $value)
		{
			$param[$key] = !empty($param[$key])?$param[$key]:"";
		}
		return $this->clsRest->insert($param);
	}
	//
	public function inserts()
	{
		
	}
	//
	
	public function updateRestaurant($param = array())
	{
		if(!isset($param['id']))
			return false;
		$ID = $param['id'];
		$result = $this->selectRestaurant($ID);
		if(empty($result))
			return false;
		foreach($param as $key => $value)
		{
			if (isset($result[$key]))
			{
				if($key == "Rate"){
					$result[$key] = $this->sumRate($result[$key],$result["NumberVote"],$value);
					$result['NumberVote'] = $result['NumberVote']+1;
				}
				else
					$result[$key] = $value;
			}
		}
		return $this->clsRest->updates($result,$ID);
	}
	
	public function getAllCategory()
	{
		return $this->clsCategory->selectAll();
	}
	
	public function getRestaurant($id)
	{
		$image = $this->clsCategory->select($id);
		$rootPath = $image['rootPath'].$image['Description'].$image['Type'];
		
		$imageString = file_get_contents($rootPath);
		$imgEncode = base64_encode($imageString);
		
		$dataRes = $this->selectRestaurant($id);
		$data = array('Status'=>'Success', 'Object'=> $result, 'Image'=> $im1, 'Promotion'=>null);
		return $data;
	}
	
	public function getAllRestaurant($id ='')
	{
		$dataRes = $this->selectAll();
		$dataImage = $this->getAllCategory();
		foreach ($dataRes as $key => $value)
		{
			$webPath = $dataImage[$key]['webPath'].$dataImage[$key]['Description'].$dataImage[$key]['Type'];// Tao duong dan den file picture
			//$imageString = file_get_contents($rootPath);//Doc file thanh String
			//$imgEncode = base64_encode($imageString); // Encode ve base64
			$dataRes[$key]['Image'] = $webPath;//$imgEncode; // Dua vao mang
		}
		$result =array('Status'=>'Success', 'Object'=>$dataRes);
		return $result;
	}
	
	public function sumRate($Rate,$number,$newValue)
	{
		$result = (($Rate*$number + $newValue)/($number+1));
		return number_format($result,1);
	}
}
?>